package sysmessage

import (
	"log"
	"net/http"

	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}

func setUp() {
	http.HandleFunc("/ws", handleWebSocket)
	http.ListenAndServe(":8080", nil)
}

func handleWebSocket(w http.ResponseWriter, r *http.Request) {
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println("WebSocket upgrade error:", err)
		return
	}
	defer conn.Close()

	for {
		// 从客户端接收消息
		messageType, reader, err := conn.NextReader()
		if err != nil {
			log.Println("Failed to read message:", err)
			break
		}

		// 判断消息类型
		switch messageType {
		case websocket.TextMessage:
			handleTextMessage(reader)
		case websocket.BinaryMessage:
			handleBinaryMessage(reader, conn)
		case websocket.CloseMessage:
			return
		}
	}
}
